//
//  GYXNetworkManager+Extensions.swift
//  GYXWeibo
//
//  Created by Twisal on 2017/1/17.
//  Copyright © 2017年 Twisal. All rights reserved.
//

import Foundation

// MARK: - 获取微博网络数据的方法
extension GYXNetworkManager {
    
    /// 获取微博的数据
    ///
    /// - Parameters:
    ///   - since_id: 若指定此参数，则返回ID比since_id大的微博（即比since_id时间晚的微博），默认为0。
    ///   - max_id: 若指定此参数，则返回ID小于或等于max_id的微博，默认为0。
    ///   - completion: 完成回调
    func loadStatusList(since_id: Int64 = 0, max_id: Int64 = 0, completion: @escaping (_ statusList: [[String : AnyObject]]?, _ isSuccess: Bool) -> ()) {
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
        
        let params = ["since_id": "\(since_id)",
                      "max_id": "\(max_id > 0 ? (max_id - 1) : 0)"] // 这样处理防止数据重复或者为-1的情况
        tokenRequest(URLString: urlString, parameters: params as [String : AnyObject]?) { (json, isSuccess) in
            let result = json?["statuses"] as? [[String: AnyObject]]
            completion(result, isSuccess)
        }
    }
    
    
    /// 获取微博的未读数量
    ///
    /// - Parameter completion: 回调
    func loadUnreadStatusCount(completion: @escaping (_ count: Int) -> () ) {
        
        guard let uid = userAccount.uid else {
            return
        }
        let urlString = "https://rm.api.weibo.com/2/remind/unread_count.json"
        let params = ["uid": uid]
        tokenRequest(URLString: urlString, parameters: params as [String : AnyObject]?) { (json, isSuccess) in
            let dict = json as? [String: AnyObject]
            let count = dict?["status"] as? Int
            completion(count ?? 0)
        }
    }
}


// MARK: - 发布微博
extension GYXNetworkManager {
    
    func postStatus(text: String, image: UIImage?, completion: @escaping (_ result: [String : AnyObject]?, _ isSuccess: Bool) -> ()) {
        // 1. url
        let urlString: String
        
        // 根据是否有图像，选择不同的接口地址
        if image == nil {
            urlString = "https://api.weibo.com/2/statuses/update.json"
        } else {
            urlString = "https://upload.api.weibo.com/2/statuses/upload.json"
        }
        
        // 2. 参数字典
        let params = ["status": text]
        
        // 3. 如果图像不为空，需要设置 name 和 data
        var name: String?
        var data: Data?
        
        if image != nil {
            name = "pic"
            data = UIImagePNGRepresentation(image!)
        }
        
        // 4. 发起网络请求
        tokenRequest(method: .POST, URLString: urlString, parameters: params as [String : AnyObject]?, name: name, data: data) { (json, isSuccess) in
            completion(json as? [String: AnyObject], isSuccess)
        }
        
    }
}

// MARK: - 获取用户信息
extension GYXNetworkManager {
    func loadUserInfo(completion: @escaping (_ dict: [String : AnyObject]) -> ()) {
        guard let uid = userAccount.uid else {
            return
        }
        let urlString = "https://api.weibo.com/2/users/show.json"
        let params = ["uid": uid]
        tokenRequest(URLString: urlString, parameters: params as [String : AnyObject]?) { (json, isSuccess) in
            completion((json as? [String : AnyObject]) ?? [:])
        }
    }
}


// MARK: - 获取accessToken
extension GYXNetworkManager {
    
    /// 获取微博访问令牌
    ///
    /// - Parameter code: 从回调中渠道的授权码
    /// - completion: 完成回调
    func loadAccessToken(code: String, completion: @escaping (_ isSuccess: Bool) -> ()) {
        let urlString = "https://api.weibo.com/oauth2/access_token"
        let params = ["client_id" : WBAppKey,
                      "client_secret" : WBAppSecret,
                      "grant_type" : "authorization_code",
                      "code" : code,
                      "redirect_uri" : WBRedirectUri]
        request(method: .POST, URLString: urlString, parameters: params as [String : AnyObject]?) { (json, isSuccess) in
            // 字典转模型
            self.userAccount.yy_modelSet(with: json as! [AnyHashable : Any])

            // 获取用户信息
            self.loadUserInfo(completion: { (dict) in
                // 再次字典转模型
                self.userAccount.yy_modelSet(with: dict)
                // 保存用户信息
                self.userAccount.saveAccount()
                print(self.userAccount)
                // 完成回调
                completion(isSuccess)
            })
        }
    }
}
